
package com.probiz.estoresa.catalog.web.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.ModelAndView;

import com.probiz.estore.catalog.model.BaseCategory;
import com.probiz.estore.catalog.model.VirtualCategoryFullyModel;
import com.probiz.estore.catalog.service.ProductCategoryManager;
import com.probiz.estore.catalog.service.VirtualCategoryManager;
import com.probiz.estore.common.model.catalog.VirtualCategory;
import com.probiz.estore.common.model.other.Tag;
import com.probiz.estore.core.controller.GenericStoreAdminController;
import com.probiz.estore.core.exception.ApplicationException;
import com.probiz.estore.other.service.TagManager;
import com.probiz.estore.product.service.BrandManager;
import com.probiz.estore.product.service.ProdMainManager;
import com.probiz.estore.product.service.ProductManager;
import com.probiz.estore.product.service.ProductTypeManager;
import com.probiz.estore.webapp.util.RequestUtil;

public class VirtualCategoryController extends GenericStoreAdminController<VirtualCategory> {
	private VirtualCategoryManager			virtualCategoryManager			= null;
	private ProductManager					productManager					= null;
	private ProdMainManager					prodMainManager					= null;
	private ProductCategoryManager productCategoryManager = null;
	private BrandManager brandManager = null;
	private ProductTypeManager productTypeManager = null;
	private TagManager tagManager = null;

	
	public void setVirtualCategoryManager(
			VirtualCategoryManager virtualCategoryManager) {
		this.virtualCategoryManager = virtualCategoryManager;
	}

	public void setProductManager(ProductManager productManager) {
		this.productManager = productManager;
	}

	public void setProdMainManager(ProdMainManager prodMainManager) {
		this.prodMainManager = prodMainManager;
	}

	
	public void setProductCategoryManager(
			ProductCategoryManager productCategoryManager) {
		this.productCategoryManager = productCategoryManager;
	}

	public void setBrandManager(BrandManager brandManager) {
		this.brandManager = brandManager;
	}

	public void setProductTypeManager(ProductTypeManager productTypeManager) {
		this.productTypeManager = productTypeManager;
	}
	

	public void setTagManager(TagManager tagManager) {
		this.tagManager = tagManager;
	}

	protected String getEntityName(VirtualCategory entity) {
		return entity.getVirtualCategoryName();
	}


	protected void initController() throws Exception {
		mgr = virtualCategoryManager;
	}
	

	public ModelAndView defaultAction(HttpServletRequest request,
			HttpServletResponse response) {
		ModelAndView mv = new ModelAndView("catalog/virtualCategoryList");
		VirtualCategory treeRoot = virtualCategoryManager.getById(1);
		Set<VirtualCategory> categorySet = treeRoot.getChildren();
		List<VirtualCategory> categoryList = new ArrayList<VirtualCategory>();
		categoryList.addAll(categorySet);
		mv.addObject("categoryList", categoryList);
		mv.addObject("treeRoot", treeRoot);
		return mv;
	}
	
	/**
	 * 获取树节点，ajax方式
	 * @param request
	 * @param response
	 * @return
	 */
	public ModelAndView getTreeItems(HttpServletRequest request,HttpServletResponse response) {
		ModelAndView mv = new ModelAndView("/catalog/include/virtualCategoryTreeAjax");
		String categoryId = RequestUtil.getParameterNullSafe(request, "categoryId");
		VirtualCategory parent = virtualCategoryManager.getById(Integer.valueOf(categoryId));
		Set<VirtualCategory> categorySet = parent.getChildren();
		List<VirtualCategory> categoryList = new ArrayList<VirtualCategory>();
		categoryList.addAll(categorySet);
		mv.addObject("categoryList",categoryList);
		return mv;
		
	}

	public ModelAndView edit(HttpServletRequest request,
			HttpServletResponse response) {
		ModelAndView mv = new ModelAndView("catalog/virtualCategoryForm");

		Integer categoryId = RequestUtil.getInteger(request, "categoryId");
		if (null != categoryId) {
			// case:编辑
			VirtualCategory category = virtualCategoryManager.getById(categoryId);
			mv.addObject("category", category);
		} else {
			// case:新增
			Integer parentCategoryId = RequestUtil.getInteger(request,"parentCategoryId");
			VirtualCategory parentCategory = virtualCategoryManager.getById(parentCategoryId);
			mv.addObject("parentCategory", parentCategory);
			VirtualCategory category = new VirtualCategory();
			Short categoryType = Short.valueOf(RequestUtil.getParameterNullSafe(request, "categoryType"));
			category.setParent(parentCategory);
			category.setCategoryType(categoryType);
			mv.addObject("category", category);
		}
		
		mv.addObject("productTypeList",productTypeManager.listAll());
		mv.addObject("brandList", brandManager.listAll());
		List<BaseCategory> productCategoryList = productCategoryManager.getCategoryList(null, 10);
		mv.addObject("productCategoryList", productCategoryList);
		mv.addObject("tagList", tagManager.getAllTagByModule(Tag.MODULE_PRODUCT));

		return mv;
	}

	public ModelAndView add(HttpServletRequest request,	HttpServletResponse response) {
		return edit(request, response);
	}

	public ModelAndView selectType(HttpServletRequest request,HttpServletResponse response) {
		return new ModelAndView("catalog/virtualCategoryFormSelectType");
	}

	/**
	 * 按categoryIds的顺序更新目录sortOrder
	 * 
	 * @param request
	 *            request
	 * @param response
	 *            response
	 * @return modelAndView
	 */
	public ModelAndView updateCategoriesSortOrder(HttpServletRequest request,HttpServletResponse response) {
		Integer[] categoryIds = RequestUtil.getIntegerArrayNullSafe(request,	"categoryIds");
		// MethodUtils.invokeMethod(mgr, "updateCategoriesSortOrder", new
		// Object[]{categoryIds});
		virtualCategoryManager.updateCategoriesSortOrder(categoryIds);
		return null;
	}

	/**
	 * 前置绑定，避免验证错误
	 * 
	 * @param entity
	 *            实体
	 */
	private void bindReady(VirtualCategory entity) {
		if (null == entity.getCategoryId()) {
			// case:新增
			entity.setStatus(VirtualCategory.STATUS_ACTIVE);
			entity.setSortOrder(VirtualCategory.SORTORDER_DEFAULT_VALUE);
		}
	}

	/*
	 * 保存前的检验和赋值.保存目录判断目录Code是否重复
	 */
	protected void preSave(HttpServletRequest request, VirtualCategory entity,
			BindException errors) {
		// start:赋值dispalyFlag
		String[] displayFlagArray = RequestUtil.getParameterValuesNullSafe(
				request, "displayFlag");
		StringBuffer displayFlag = new StringBuffer();
		for (String flag : displayFlagArray) {
			displayFlag.append(flag);
		}
		entity.setDisplayFlag(displayFlag.toString());
		// end:赋值dispalyFlag

	}

	public ModelAndView save(HttpServletRequest request,HttpServletResponse response) throws Exception {

		// 取得Form对应的Model
		VirtualCategory entity = formBackingObject(request);
		BindException errors = null;
		Map<String, Object> data = new HashMap<String, Object>();
		try {
			bindReady(entity);
			ServletRequestDataBinder binder = bindAndValidate(request, entity);
			// noinspection ThrowableInstanceNeverThrown
			errors = new BindException(binder.getBindingResult());
			// 传给子类的实现，后者可以继续验证和加入错误到errors
			preSave(request, entity, errors);
			if (!errors.hasErrors()) {// 里面如果出错应该抛出异常
				Map<String, Object> saveData = virtualCategoryManager.saveFully(getVirtualCategoryFullyModel(request,entity, data));
				data.putAll(saveData);
			}
		} catch (ApplicationException e) {
			handleApplicationException(errors, e);
		}
		buildReturnInfo(data, entity, request);

		return getModelAndAjaxJsonView(data);
	}

	// 构造模型，方便保存
	private VirtualCategoryFullyModel getVirtualCategoryFullyModel(HttpServletRequest request, VirtualCategory virtualCategory,Map<String, Object> data) {
		VirtualCategoryFullyModel model = new VirtualCategoryFullyModel();
		//start:构造品牌
		String[] brandIds = RequestUtil.getParameterValuesNullSafe(request, "brandIds");
		if(!ArrayUtils.isEmpty(brandIds)){
			StringBuffer sb= new StringBuffer(50);
			for(String brandId:brandIds){
				if(StringUtils.isNotBlank(brandId)){
					sb.append(brandId).append(",");
				}
			}
			if(StringUtils.isNotBlank(sb.toString())){
				virtualCategory.setFcBrands(sb.toString().substring(0, sb.length()-1));
			}else{
				virtualCategory.setFcBrands("");
			}
		}else{
			virtualCategory.setFcBrands("");
		}
		//end:构造品牌
		
		//start:构造商品类型
		String[] productTypeIds = RequestUtil.getParameterValuesNullSafe(request, "productTypeIds");
		if(!ArrayUtils.isEmpty(productTypeIds)){
			StringBuffer sb= new StringBuffer(50);
			for(String productTypeId:productTypeIds){
				if(StringUtils.isNotBlank(productTypeId)){
					sb.append(productTypeId).append(",");
				}
			}
			if(StringUtils.isNotBlank(sb.toString())){
				virtualCategory.setFcProductTypes(sb.toString().substring(0, sb.length()-1));
			}else{
				virtualCategory.setFcProductTypes("");
			}
		}else{
			virtualCategory.setFcProductTypes("");
		}
		//end:构造商品类型
		
		//start:构造商品目录
		String[] productCategoryIds = RequestUtil.getParameterValuesNullSafe(request, "productCategoryIds");
		if(!ArrayUtils.isEmpty(productCategoryIds)){
			StringBuffer sb= new StringBuffer(50);
			for(String productCategoryId:productCategoryIds){
				if(StringUtils.isNotBlank(productCategoryId)){
					sb.append(productCategoryId).append(",");
				}
			}
			if(StringUtils.isNotBlank(sb.toString())){
				virtualCategory.setFcProductCategories(sb.toString().substring(0, sb.length()-1));
			}else{
				virtualCategory.setFcProductCategories("");
			}
		}else{
			virtualCategory.setFcProductCategories("");
		}
		//end:构造商品目录
		
		//start:构造标签
		String[] tagIds = RequestUtil.getParameterValuesNullSafe(request, "tagIds");
		if(!ArrayUtils.isEmpty(tagIds)){
			StringBuffer sb= new StringBuffer(50);
			for(String tagId:tagIds){
				if(StringUtils.isNotBlank(tagId)){
					sb.append(tagId).append(",");
				}
			}
			if(StringUtils.isNotBlank(sb.toString())){
				virtualCategory.setFcTags(sb.toString().substring(0, sb.length()-1));
			}else{
				virtualCategory.setFcTags("");
			}
		}else{
			virtualCategory.setFcTags("");
		}
		//end:构造标签
		
		// --------- start: 绑定推荐关联商品----------------
		String[] recommendedProductIds = RequestUtil.getParameterValuesNullSafe(request, "recommendedProductIds");
		model.setRecommendedProductIds(recommendedProductIds);
		// --------- end: 绑定推荐关联商品----------------
		
		model.setVirtualCategory(virtualCategory);

		return model;
	}

	/**
	 * 按categoryId删除目录
	 */
	public ModelAndView delete(HttpServletRequest request,HttpServletResponse response) throws Exception {
		Integer categoryId = RequestUtil.getInteger(request, "categoryId");
		VirtualCategory virtualCategory = virtualCategoryManager.getById(categoryId);
		Map<String, Object> data = virtualCategoryManager.deleteFully(virtualCategory);
		return getModelAndAjaxJsonView(data);
	}

	/**
	 * 加入返回参数
	 * 
	 * @param data
	 * @param product
	 * @param request
	 */
	private void buildReturnInfo(Map<String, Object> data,
			VirtualCategory entity, HttpServletRequest request) {
		data.put("categoryId", entity.getCategoryId());
		data.put("categoryCode", entity.getCategoryCode());
		data.put("categoryType", entity.getCategoryType());
		data.put("categoryName", entity.getCategoryName());
		data.put("depth", entity.getDepth());
		data.put("itemCount", entity.getItemCount());
		data.put("activeItemCount", entity.getActiveItemCount());

	}

}
